package com.woniuxy.flowable.service.impl;

import com.woniuxy.flowable.service.FlowAbleService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Flowable工作流服务实现类
 * @author woniuxy
 */
@Slf4j
@Service
public class FlowAbleServiceImpl implements FlowAbleService {

    @Autowired
    private RuntimeService runtimeService;
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private RepositoryService repositoryService;
    
    @Autowired
    private HistoryService historyService;
    
    @Autowired
    private IdentityService identityService;
    
    @Autowired
    private ProcessEngine processEngine;
    
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String startFlowAble(String XMLPath, String flowName, Map<String, Object> info, Object rolesDto, Map<String, Object> conditions) {
        try {
            // 合并所有变量
            Map<String, Object> variables = new HashMap<>();
            if (info != null) {
                variables.putAll(info);
            }
            if (conditions != null) {
                variables.putAll(conditions);
            }
            
            // 启动流程实例
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(flowName, variables);
            return processInstance.getId();
        } catch (Exception e) {
            throw new RuntimeException("启动流程失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public ProcessInstance startProcessInstanceByKey(String processDefinitionKey, String businessKey, Map<String, Object> variables) {
        try {
            // 启动流程实例
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
            return processInstance;
        } catch (Exception e) {
            throw new RuntimeException("启动流程失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<Map<String, Object>> queryUserFlow(String userName) {
        // 查询直接分配给用户的任务（只查询活跃任务）
        List<Task> assignedTasks = taskService.createTaskQuery()
                .taskAssignee(userName)
                .active()
                .orderByTaskCreateTime()
                .desc()
                .list();
        
        // 查询用户所属组的候选任务（只查询活跃任务）
        List<Task> candidateTasks = taskService.createTaskQuery()
                .taskCandidateUser(userName)
                .active()
                .orderByTaskCreateTime()
                .desc()
                .list();
        
        // 合并两个列表，去重
        Set<String> taskIds = new HashSet<>();
        List<Task> allTasks = new ArrayList<>();
        
        for (Task task : assignedTasks) {
            if (!taskIds.contains(task.getId())) {
                taskIds.add(task.getId());
                allTasks.add(task);
            }
        }
        
        for (Task task : candidateTasks) {
            if (!taskIds.contains(task.getId())) {
                taskIds.add(task.getId());
                allTasks.add(task);
            }
        }
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (Task task : allTasks) {
            // 再次确认流程实例仍然活跃（双重保险）
            org.flowable.engine.runtime.ProcessInstance processInstance = 
                runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            
            // 如果流程实例不存在，说明流程已结束，跳过这个任务
            if (processInstance == null) {
                log.debug("跳过已结束流程的任务，任务ID：{}，流程实例ID：{}", 
                    task.getId(), task.getProcessInstanceId());
                continue;
            }
            
            Map<String, Object> taskInfo = new HashMap<>();
            taskInfo.put("taskId", task.getId());
            taskInfo.put("taskName", task.getName());
            taskInfo.put("assignee", task.getAssignee());
            taskInfo.put("createTime", task.getCreateTime());
            taskInfo.put("processInstanceId", task.getProcessInstanceId());
            taskInfo.put("processDefinitionId", task.getProcessDefinitionId());
            taskInfo.put("businessKey", processInstance.getBusinessKey());
            result.add(taskInfo);
        }
        
        log.info("用户 {} 的待办任务数量：{}", userName, result.size());
        return result;
    }

    /**
     * 查询指定用户的已完成任务列表
     *
     * @param userName 用户名称
     * @return 已完成的任务列表，每个任务以键值对形式存储，包含任务ID、任务名称、任务执行人、任务开始时间、任务结束时间、流程实例ID
     * @throws ParseException 日期格式解析异常
     */
    @Override
    public List<Map<String, Object>> queryCompletedTasks(String userName) throws ParseException {
        List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(userName)
                .finished()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .list();
        
        List<Map<String, Object>> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (HistoricTaskInstance task : tasks) {
            Map<String, Object> taskInfo = new HashMap<>();
            taskInfo.put("taskId", task.getId());
            taskInfo.put("taskName", task.getName());
            taskInfo.put("assignee", task.getAssignee());
            taskInfo.put("startTime", sdf.format(task.getStartTime()));
            taskInfo.put("endTime", sdf.format(task.getEndTime()));
            taskInfo.put("processInstanceId", task.getProcessInstanceId());
            result.add(taskInfo);
        }
        return result;
    }

    @Override
    public void acceptFlow(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        
        Map<String, Object> variables = new HashMap<>();
        variables.put("approved", true);
        variables.put("outcome", "通过");
        
        
        try {
            // 完成任务
            taskService.complete(taskId, variables);
            
            // 立即更新订单状态
            updateOrderStepAfterApproval(task.getProcessInstanceId(), task.getTaskDefinitionKey());
            
            // 等待一下让流程引擎处理
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
            
            // 检查流程是否继续
            List<Task> activeTasks = taskService.createTaskQuery()
                .processInstanceId(task.getProcessInstanceId())
                .active()
                .list();
            
            // 如果流程没有自动推进，尝试手动推进
            if (activeTasks.isEmpty()) {
                org.flowable.engine.history.HistoricProcessInstance historicInstance = 
                    historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                if (historicInstance != null) {
                }
            }
            
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public void rejectFlow(String taskId, String reason) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        String processInstanceId = task.getProcessInstanceId();
        String taskName = task.getName(); // 获取当前任务名称，用于确定拒绝步骤
        
        try {
            // 先获取流程实例信息
            org.flowable.engine.runtime.ProcessInstance processInstance = 
                runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            
            if (processInstance == null) {
                throw new RuntimeException("流程实例不存在");
            }
            
            // 获取业务键（订单ID）
            String orderId = processInstance.getBusinessKey();
            
            // 设置流程变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("approved", false);
            variables.put("outcome", "驳回");
            variables.put("rejectReason", reason);
            
            // 完成任务
            taskService.complete(taskId, variables);
            
            // 立即终止流程实例，这会自动取消所有相关的活跃任务
            runtimeService.deleteProcessInstance(processInstanceId, "审批被拒绝: " + reason);
            
            // 立即更新订单状态为已拒绝，传递当前任务名称
            updateOrderStatusAfterReject(processInstanceId, reason, taskName);
            
            log.info("订单审批拒绝成功，流程实例ID：{}，订单ID：{}，拒绝原因：{}，拒绝步骤：{}", 
                processInstanceId, orderId, reason, taskName);
            
        } catch (Exception e) {
            log.error("拒绝审批失败，任务ID：{}，流程实例ID：{}，错误：{}", 
                taskId, processInstanceId, e.getMessage(), e);
            throw new RuntimeException("拒绝审批失败: " + e.getMessage());
        }
    }

    @Override
    public String testDynamicApproval() {
        return "动态审批功能测试成功";
    }
    
    /**
     * 直接推进流程到下一个节点
     */
    public void advanceProcessToNextStep(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        
        try {
            // 完成任务
            taskService.complete(taskId);
            
            // 立即更新订单状态
            updateOrderStepAfterApproval(task.getProcessInstanceId(), task.getTaskDefinitionKey());
            
            // 检查新的活跃任务
            List<Task> activeTasks = taskService.createTaskQuery()
                .processInstanceId(task.getProcessInstanceId())
                .active()
                .list();
            
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 审批完成后立即更新订单步骤
     */
    private void updateOrderStepAfterApproval(String processInstanceId, String taskDefinitionKey) {
        try {
            // 获取流程实例的业务键（订单ID）
            org.flowable.engine.runtime.ProcessInstance processInstance = 
                runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            
            if (processInstance != null && processInstance.getBusinessKey() != null) {
                String orderId = processInstance.getBusinessKey();
                String nextStep = getNextStepByTaskDefinitionKey(taskDefinitionKey);
                
                
                if (nextStep != null) {
                    // 调用订单服务更新步骤
                    String orderServiceUrl = "http://localhost:8007/api/orders/callback/update-step";
                    
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("orderId", orderId);
                    requestBody.put("currentStep", nextStep);
                    requestBody.put("processInstanceId", processInstanceId);
                    
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
                    
                    restTemplate.postForObject(orderServiceUrl, request, String.class);
                    
                } else {
                    // 流程完成，更新为已通过
                    String orderServiceUrl = "http://localhost:8007/api/orders/callback/approve-success";
                    
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("orderId", orderId);
                    requestBody.put("status", "APPROVED");
                    
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
                    
                    restTemplate.postForObject(orderServiceUrl, request, String.class);
                    
                }
            }
        } catch (Exception e) {
        }
    }
    
    /**
     * 根据任务定义Key获取下一步
     */
    private String getNextStepByTaskDefinitionKey(String taskDefinitionKey) {
        Map<String, String> stepMap = new HashMap<>();
        stepMap.put("officeBusinessTask", "地区经理审批");
        stepMap.put("regionalManagerTask", "大区经理审批");
        stepMap.put("regionalDirectorTask", "市场部审批");
        stepMap.put("marketingTask", "物流总监审批");
        stepMap.put("logisticsDirectorTask", "销售总监审批");
        stepMap.put("salesDirectorTask", "公司商务审批");
        stepMap.put("companyBusinessTask", null); // 最后一步，返回null表示完成
        
        return stepMap.get(taskDefinitionKey);
    }
    
    /**
     * 拒绝后立即更新订单状态
     */
    private void updateOrderStatusAfterReject(String processInstanceId, String reason, String taskName) {
        try {
            // 由于流程实例已经被删除，我们需要从历史记录中获取业务键
            org.flowable.engine.history.HistoricProcessInstance historicInstance = 
                historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            
            if (historicInstance != null && historicInstance.getBusinessKey() != null) {
                String orderId = historicInstance.getBusinessKey();
                
                // 调用订单服务更新状态为已拒绝
                String orderServiceUrl = "http://localhost:8007/api/orders/callback/approve-reject";
                
                // 使用传入的任务名称确定拒绝步骤
                String rejectStep = mapTaskNameToStepName(taskName);
                
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("orderId", orderId);
                requestBody.put("status", "REJECTED");
                requestBody.put("rejectReason", reason);
                requestBody.put("rejectStep", rejectStep);
                requestBody.put("processInstanceId", processInstanceId);
                
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
                
                String response = restTemplate.postForObject(orderServiceUrl, request, String.class);
                log.info("订单状态更新成功，订单ID：{}，拒绝步骤：{}，响应：{}", orderId, rejectStep, response);
            } else {
                log.warn("无法找到流程实例的历史记录，流程实例ID：{}", processInstanceId);
            }
        } catch (Exception e) {
            log.error("更新订单状态失败，流程实例ID：{}，错误：{}", processInstanceId, e.getMessage(), e);
            // 记录错误但不抛出异常，避免影响主流程
        }
    }
    
    /**
     * 从流程实例中获取拒绝的步骤
     */
    private String getRejectStepFromProcessInstance(String processInstanceId) {
        try {
            // 查询流程实例的历史任务，找到最后一个被拒绝的任务
            List<HistoricTaskInstance> historicTasks = 
                historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .finished()
                    .orderByHistoricTaskInstanceEndTime()
                    .desc()
                    .list();
            
            // 查找最后一个被拒绝的任务
            for (HistoricTaskInstance task : historicTasks) {
                // 获取任务的流程变量
                List<HistoricVariableInstance> variables = 
                    historyService.createHistoricVariableInstanceQuery()
                        .processInstanceId(processInstanceId)
                        .taskId(task.getId())
                        .list();
                
                // 检查是否有拒绝的变量
                for (HistoricVariableInstance variable : variables) {
                    if ("approved".equals(variable.getVariableName()) && 
                        Boolean.FALSE.equals(variable.getValue())) {
                        // 找到拒绝的任务，根据任务名称确定拒绝步骤
                        log.info("找到拒绝的任务: {}, 任务名称: {}", task.getId(), task.getName());
                        return mapTaskNameToStepName(task.getName());
                    }
                }
            }
            
            // 如果没有找到明确的拒绝任务，尝试从当前活跃任务推断
            // 当流程被拒绝时，可能当前任务就是被拒绝的任务
            List<Task> activeTasks = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .active()
                .list();
            
            if (!activeTasks.isEmpty()) {
                // 如果还有活跃任务，说明拒绝可能发生在当前任务
                Task currentTask = activeTasks.get(0);
                log.info("从当前活跃任务推断拒绝步骤: {}", currentTask.getName());
                return mapTaskNameToStepName(currentTask.getName());
            }
            
            // 如果都没有找到，返回默认值
            log.warn("无法确定拒绝步骤，使用默认值: 地区经理审批");
            return "地区经理审批";
            
        } catch (Exception e) {
            log.warn("获取拒绝步骤失败: {}", e.getMessage());
            return "地区经理审批";
        }
    }
    
    /**
     * 将任务名称映射为步骤名称
     */
    private String mapTaskNameToStepName(String taskName) {
        Map<String, String> taskStepMap = new HashMap<>();
        taskStepMap.put("地区经理审批", "地区经理审批");
        taskStepMap.put("大区经理审批", "大区经理审批");
        taskStepMap.put("市场部审批", "市场部审批");
        taskStepMap.put("物流总监审批", "物流总监审批");
        taskStepMap.put("销售总监审批", "销售总监审批");
        taskStepMap.put("公司商务审批", "公司商务审批");
        
        return taskStepMap.getOrDefault(taskName, "地区经理审批");
    }

    @Override
    public Map<String, Object> getApprovalHistory(Map<String, Object> params) {
        String userName = (String) params.get("userName");
        int page = (Integer) params.getOrDefault("page", 1);
        int size = (Integer) params.getOrDefault("size", 20);
        String orderNo = (String) params.get("orderNo");
        String customerName = (String) params.get("customerName");
        String approvalResult = (String) params.get("approvalResult");
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        
        // 查询历史任务 - 只查询用户自己审批过的任务
        HistoricTaskInstanceQuery query = 
            historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(userName)  // 只查询分配给当前用户的任务
                .finished()              // 只查询已完成的任务
                .orderByHistoricTaskInstanceEndTime()
                .desc();
        
        // 添加过滤条件
        if (orderNo != null && !orderNo.trim().isEmpty()) {
            query.processInstanceBusinessKey(orderNo);
        }
        
        if (startDate != null && !startDate.trim().isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                query.taskCompletedAfter(sdf.parse(startDate));
            } catch (ParseException e) {
                // 忽略日期解析错误
            }
        }
        
        if (endDate != null && !endDate.trim().isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date endDateTime = sdf.parse(endDate);
                Calendar cal = Calendar.getInstance();
                cal.setTime(endDateTime);
                cal.add(Calendar.DAY_OF_MONTH, 1);
                query.taskCompletedBefore(cal.getTime());
            } catch (ParseException e) {
                // 忽略日期解析错误
            }
        }
        
        // 分页查询
        List<HistoricTaskInstance> historicTasks = 
            query.listPage((page - 1) * size, size);
        
        long total = query.count();
        
        List<Map<String, Object>> records = new ArrayList<>();
        for (HistoricTaskInstance task : historicTasks) {
            Map<String, Object> record = new HashMap<>();
            record.put("taskId", task.getId());
            record.put("taskName", task.getName());
            record.put("processInstanceId", task.getProcessInstanceId());
            record.put("approvalTime", task.getEndTime());
            // 获取流程实例的业务键
            String businessKey = null;
            try {
                org.flowable.engine.history.HistoricProcessInstance historicProcessInstance = 
                    historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                if (historicProcessInstance != null) {
                    businessKey = historicProcessInstance.getBusinessKey();
                }
            } catch (Exception e) {
                log.warn("获取流程实例业务键失败: {}", e.getMessage());
            }
            record.put("orderId", businessKey);
            
            // 获取流程变量判断审批结果
            List<HistoricVariableInstance> variables = 
                historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .list();
            
            boolean approved = true;
            String rejectReason = null;
            for (HistoricVariableInstance variable : variables) {
                if ("approved".equals(variable.getVariableName())) {
                    approved = (Boolean) variable.getValue();
                }
                if ("rejectReason".equals(variable.getVariableName())) {
                    rejectReason = (String) variable.getValue();
                }
            }
            
            record.put("approvalResult", approved ? "approved" : "rejected");
            record.put("rejectReason", rejectReason);
            
            // 获取订单信息
            if (businessKey != null) {
                try {
                    // 调用订单服务获取订单详情
                    String orderId = businessKey;
                    String orderServiceUrl = "http://localhost:8007/api/orders/" + orderId;
                    
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<String> request = new HttpEntity<>(headers);
                    
                    try {
                        // 尝试获取订单详情
                        String response = restTemplate.getForObject(orderServiceUrl, String.class);
                        if (response != null && !response.trim().isEmpty()) {
                            // 这里可以解析JSON响应获取订单信息
                            // 暂时使用业务键作为订单编号
                            record.put("orderNo", orderId);
                            record.put("customerName", "客户名称"); // 需要解析JSON获取
                        } else {
                            record.put("orderNo", orderId);
                            record.put("customerName", "未知客户");
                        }
                    } catch (Exception e) {
                        // 如果订单服务不可用，使用默认值
                        record.put("orderNo", orderId);
                        record.put("customerName", "未知客户");
                    }
                } catch (Exception e) {
                    record.put("orderNo", businessKey);
                    record.put("customerName", "未知客户");
                }
            }
            
            // 应用审批结果过滤
            if (approvalResult != null && !approvalResult.trim().isEmpty()) {
                String result = approved ? "approved" : "rejected";
                if (!approvalResult.equals(result)) {
                    continue;
                }
            }
            
            // 应用客户名称过滤
            if (customerName != null && !customerName.trim().isEmpty()) {
                String customer = (String) record.get("customerName");
                if (customer == null || !customer.contains(customerName)) {
                    continue;
                }
            }
            
            records.add(record);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getApprovalStatistics(String userName) {
        // 查询用户的所有历史任务 - 只统计用户自己审批过的任务
        List<HistoricTaskInstance> allTasks = 
            historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(userName)  // 只查询分配给当前用户的任务
                .finished()              // 只查询已完成的任务
                .list();
        
        int totalApprovals = allTasks.size();
        int approvedCount = 0;
        int rejectedCount = 0;
        
        for (HistoricTaskInstance task : allTasks) {
            // 获取流程变量判断审批结果
            List<HistoricVariableInstance> variables = 
                historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .list();
            
            boolean approved = true;
            for (HistoricVariableInstance variable : variables) {
                if ("approved".equals(variable.getVariableName())) {
                    approved = (Boolean) variable.getValue();
                    break;
                }
            }
            
            if (approved) {
                approvedCount++;
            } else {
                rejectedCount++;
            }
        }
        
        double approvalRate = totalApprovals > 0 ? 
            Math.round((double) approvedCount / totalApprovals * 100 * 100) / 100.0 : 0;
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalApprovals", totalApprovals);
        result.put("approvedCount", approvedCount);
        result.put("rejectedCount", rejectedCount);
        result.put("approvalRate", approvalRate);
        
        return result;
    }

    @Override
    public void addUserToDistrictManagerGroup(String userName) {
        // 创建用户组（如果不存在）
        String groupId = "district_manager_group";
        try {
            identityService.createGroupQuery().groupId(groupId).singleResult();
        } catch (Exception e) {
            identityService.newGroup(groupId);
            identityService.saveGroup(identityService.createGroupQuery().groupId(groupId).singleResult());
        }
        
        // 创建用户（如果不存在）
        try {
            identityService.createUserQuery().userId(userName).singleResult();
        } catch (Exception e) {
            identityService.newUser(userName);
            identityService.saveUser(identityService.createUserQuery().userId(userName).singleResult());
        }
        
        // 将用户添加到组
        identityService.createMembership(userName, groupId);
    }

    @Override
    public void removeUserFromDistrictManagerGroup(String userName) {
        String groupId = "district_manager_group";
        identityService.deleteMembership(userName, groupId);
    }

    @Override
    public boolean hasDistrictManagerPermission(String userName) {
        String groupId = "district_manager_group";
        return identityService.createGroupQuery()
                .groupMember(userName)
                .groupId(groupId)
                .count() > 0;
    }

    @Override
    public void completeFlow(String taskId, Map<String, Object> variables) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        taskService.complete(taskId, variables);
    }

    @Override
    public List<String> getLocalOperator(String deploymentId) {
        List<String> assignees = new ArrayList<>();
        try {
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceId(deploymentId)
                    .list();
            
            for (Task task : tasks) {
                if (task.getAssignee() != null) {
                    assignees.add(task.getAssignee());
                } else {
                    // 获取候选用户
                    List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
                    for (IdentityLink link : identityLinks) {
                        if (link.getUserId() != null) {
                            assignees.add(link.getUserId());
                        }
                    }
                }
            }
        } catch (Exception e) {
            // 如果deploymentId实际上是processInstanceId，则按流程实例查询
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceId(deploymentId)
                    .list();
            
            for (Task task : tasks) {
                if (task.getAssignee() != null) {
                    assignees.add(task.getAssignee());
                }
            }
        }
        return assignees;
    }


    @Override
    public String syncUserToFlowable(String username, String realName, String email, String groupId) {
        try {
            // 创建或更新用户
            org.flowable.idm.api.User user = identityService.createUserQuery().userId(username).singleResult();
            if (user == null) {
                user = identityService.newUser(username);
            }
            user.setFirstName(realName);
            user.setEmail(email);
            identityService.saveUser(user);
            
            // 创建或更新用户组
            org.flowable.idm.api.Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
            if (group == null) {
                group = identityService.newGroup(groupId);
                group.setName(groupId);
                identityService.saveGroup(group);
            }
            
            // 建立用户和组的关系
            identityService.createMembership(username, groupId);
            
            return "用户同步成功";
        } catch (Exception e) {
            throw new RuntimeException("同步用户失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<Map<String, Object>> getProcessSteps(String processInstanceId) {
        try {
            List<Map<String, Object>> steps = new ArrayList<>();
            
            // 查询历史任务
            List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .orderByHistoricTaskInstanceStartTime()
                    .asc()
                    .list();
            
            for (HistoricTaskInstance task : historicTasks) {
                Map<String, Object> step = new HashMap<>();
                step.put("taskId", task.getId());
                step.put("taskName", task.getName());
                step.put("assignee", task.getAssignee());
                step.put("status", task.getEndTime() != null ? "COMPLETED" : "PENDING");
                step.put("createTime", task.getStartTime());
                step.put("endTime", task.getEndTime());
                step.put("duration", task.getDurationInMillis());
                
                // 获取审批结果
                List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery()
                        .processInstanceId(processInstanceId)
                        .taskId(task.getId())
                        .list();
                
                for (HistoricVariableInstance variable : variables) {
                    if ("approved".equals(variable.getVariableName())) {
                        step.put("result", (Boolean) variable.getValue() ? "APPROVED" : "REJECTED");
                    }
                    if ("approvalComment".equals(variable.getVariableName())) {
                        step.put("comment", variable.getValue());
                    }
                }
                
                steps.add(step);
            }
            
            return steps;
        } catch (Exception e) {
            log.error("获取流程步骤失败", e);
            throw new RuntimeException("获取流程步骤失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getProcessStatus(String processInstanceId) {
        try {
            Map<String, Object> status = new HashMap<>();
            
            // 查询流程实例
            org.flowable.engine.runtime.ProcessInstance processInstance = 
                runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            
            if (processInstance != null) {
                // 流程仍在运行
                status.put("status", "RUNNING");
                status.put("processInstanceId", processInstance.getId());
                status.put("processDefinitionId", processInstance.getProcessDefinitionId());
                status.put("businessKey", processInstance.getBusinessKey());
                
                // 查询当前活跃任务
                List<Task> activeTasks = taskService.createTaskQuery()
                        .processInstanceId(processInstanceId)
                        .active()
                        .list();
                
                List<Map<String, Object>> currentTasks = new ArrayList<>();
                for (Task task : activeTasks) {
                    Map<String, Object> taskInfo = new HashMap<>();
                    taskInfo.put("taskId", task.getId());
                    taskInfo.put("taskName", task.getName());
                    taskInfo.put("assignee", task.getAssignee());
                    taskInfo.put("createTime", task.getCreateTime());
                    currentTasks.add(taskInfo);
                }
                status.put("currentTasks", currentTasks);
                
            } else {
                // 流程已结束
                org.flowable.engine.history.HistoricProcessInstance historicInstance = 
                    historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(processInstanceId)
                        .singleResult();
                
                if (historicInstance != null) {
                    status.put("status", "COMPLETED");
                    status.put("processInstanceId", historicInstance.getId());
                    status.put("processDefinitionId", historicInstance.getProcessDefinitionId());
                    status.put("businessKey", historicInstance.getBusinessKey());
                    status.put("startTime", historicInstance.getStartTime());
                    status.put("endTime", historicInstance.getEndTime());
                    status.put("duration", historicInstance.getDurationInMillis());
                } else {
                    status.put("status", "NOT_FOUND");
                }
            }
            
            return status;
        } catch (Exception e) {
            log.error("查询流程状态失败", e);
            throw new RuntimeException("查询流程状态失败: " + e.getMessage());
        }
    }
}
